<template>
  <div style="display: flex; flex-direction: row; height: auto">
    <div :style="{ width: leftPanelWidth + 'px' }">
      <el-scrollbar height="88vh">
        <el-tree
          ref="docTree"
          :data="treeData"
          node-key="label"
          default-expand-all
          :props="defaultProps"
          :highlight-current="true"
          :current-node-key="currentNodeKey"
          @current-change="onTreeCurrentChange"
        />
      </el-scrollbar>
      <div style="display: flex; flex-direction: row; margin-left: 15px">
        <el-button
          :disabled="currentNodeKey == null || currentNodeKey.length == 0"
          >新增</el-button
        >
        <el-button :disabled="!isTableSelRevisable()">修订</el-button>
        <el-button :disabled="!isTableSelReleasable()">发起流程</el-button>
      </div>
    </div>
    <div class="resizer" @mousedown="startResize"></div>
    <div style="flex: 1">
      <div style="margin: 10px 10px 0px 10px">
        <div v-if="Number(selPaths?.length) > 0">
          <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item v-for="(path, index) in selPaths" :key="index">
              {{ path }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div v-else>未选择文档路径</div>
      </div>
      <el-divider style="margin-left: 10px" />
      <div
        style="margin: 10px; width: 400px; display: flex; flex-direction: row"
      >
        <el-input
          v-model="input2"
          class="input-with-select"
          placeholder="输入关键词搜索"
          @keyup.enter="filterTableData"
          ><template #append>
            <el-button :icon="Search" @click="filterTableData" />
          </template>
        </el-input>
      </div>
      <el-table
        :data="currentPageTableData"
        highlight-current-row
        @current-change="onTableCurrentChange"
        table-layout="auto"
        fit
        border
        style="width: 100%"
        max-height="80vh"
      >
        <el-table-column type="index" label="序号" sortable width="60px" />
        <el-table-column
          prop="PP8_TITLE1"
          show-overflow-tooltip
          label="标题1"
        />
        <el-table-column
          prop="PP8_TITLE2"
          show-overflow-tooltip
          label="标题2"
        />
        <el-table-column
          prop="PP8_TITLE3"
          show-overflow-tooltip
          label="标题3"
        />
        <el-table-column
          show-overflow-tooltip
          prop="PP8_TITLE4"
          label="标题4"
        />
        <el-table-column
          show-overflow-tooltip
          prop="PITEM_ID"
          label="管理番号"
        />
        <el-table-column
          show-overflow-tooltip
          prop="PITEM_REVISION_ID"
          label="版本"
        />
        <el-table-column show-overflow-tooltip prop="" label="强制/推荐" />
        <el-table-column
          show-overflow-tooltip
          prop="POBJECT_NAME"
          label="文书名"
        />
        <el-table-column
          show-overflow-tooltip
          prop="PP8_UPDATEDATE"
          label="最终改定日"
        />
        <el-table-column
          show-overflow-tooltip
          prop="address"
          label="有效日期"
        />
        <el-table-column fixed="right" label="查看" width="120">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="watchProps(row)"
              >属性</el-button
            >
            <el-button
              link
              type="primary"
              size="small"
              @click="watchContent(row)"
              >正文</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        layout="prev, pager, next"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
  <el-drawer v-model="createAndViewDrawer" title="基准属性" direction="rtl">
    <el-form
      :model="standardForm"
      label-width="100px"
      label-position="left"
      ref="standardFormRef"
    >
      <el-form-item label="公开标准 :">
        <el-input v-model="standardForm.gongKaiBiaoZhun" />
      </el-form-item>
      <el-form-item label="承认标准 :">
        <el-input v-model="standardForm.chengRenBiaoZhun" />
      </el-form-item>
      <el-form-item label="英语化 :">
        <el-switch v-model="standardForm.yingYuHua" />
      </el-form-item>
      <el-form-item label="中文化 :">
        <el-switch v-model="standardForm.zhongWenHua" />
      </el-form-item>
      <el-form-item label="适用性 :">
        <el-input v-model="standardForm.shiYongXing" />
      </el-form-item>
      <el-form-item label="工厂 :">
        <el-input v-model="standardForm.gongChang" />
      </el-form-item>
      <el-form-item label="商品别 :">
        <el-input v-model="standardForm.shangPinBie" />
      </el-form-item>
      <el-form-item label="管理番号 :">
        <el-input v-model="standardForm.guanliFanHao" />
      </el-form-item>
      <el-form-item label="制定日 :">
        <el-input v-model="standardForm.zhiDingRi" />
      </el-form-item>
      <el-form-item label="作成者 :">
        <el-input v-model="standardForm.zuoChengZhe" />
      </el-form-item>
      <el-form-item label="检印者 :">
        <el-input v-model="standardForm.jianYinZhe" />
      </el-form-item>
      <el-form-item label="承认者 :">
        <el-input v-model="standardForm.chengRenZhe" />
      </el-form-item>
      <el-form-item label="制定理由">
        <el-checkbox
          v-for="item in standardForm.zhiDingLiYou"
          :key="item.name"
          :label="item.name"
          v-model="item.checked"
        />
      </el-form-item>
      <el-form-item label="关联规格法规">
        <el-checkbox
          v-for="item in standardForm.guanLianGuiGeFaGui"
          :key="item.name"
          :label="item.name"
          v-model="item.checked"
        />
      </el-form-item>
      <el-form-item label="订正日 :">
        <el-input v-model="standardForm.dingZhengRi" />
      </el-form-item>
      <el-form-item label="订正No. :">
        <el-input v-model="standardForm.dingZhengNo" />
      </el-form-item>
      <el-form-item label="订正理由 :">
        <el-input v-model="standardForm.dingZhengLiYou" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
  <el-drawer v-model="standardReviseDrawer" title="基准修订" direction="ltr">
    <el-form
      :model="standardForm"
      label-width="100px"
      label-position="left"
      ref="standardFormRef"
    >
      <el-form-item label="基准编号 :">
        <el-input v-model="standardForm.gongKaiBiaoZhun" />
      </el-form-item>
      <el-form-item label="基准名称 :">
        <el-input v-model="standardForm.chengRenBiaoZhun" />
      </el-form-item>
      <el-form-item label="基准版本 :">
        <el-input v-model="standardForm.chengRenBiaoZhun" />
      </el-form-item>
      <el-form-item label="文件上传">
        <el-upload
          ref="uploadByRevise"
          class="upload-demo"
          action="/uploadUrl"
          :file-list="fileList"
          :auto-upload="false"
          :limit="1"
          :on-exceed="handleExceed"
        >
          <el-button size="small" type="primary">选取文件</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style>
.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
.split-pane {
  display: flex;
  height: 100vh;
}

.left-pane,
.right-pane {
  flex: 1;
  overflow: auto;
}

.left-pane {
  background-color: lightblue;
}

.right-pane {
  background-color: lightcoral;
}

.drag-handle {
  cursor: ew-resize;
  background-color: #ccc;
  width: 5px;
}

.ghost {
  opacity: 0.5;
}

.chosen {
  background-color: #f9f9f9;
}

.drag {
  background-color: #f9f9f9;
}
</style>
<!-- <script>
export default {
  mounted: function () {
    this.$nextTick(() => {
      (this.$refs.docTree as any).setCurrentKey("");
    });
  },
};
</script> -->
<script lang="ts" setup>
import { FormInstance, FormRules } from "element-plus";
import {
  UploadProps,
  UploadUserFile,
  UploadInstance,
  ElMessage,
  ElMessageBox,
  genFileId,
} from "element-plus";
import { ref, getCurrentInstance, nextTick, Ref, reactive } from "vue";
import { ArrowRight } from "@element-plus/icons-vue";
import { Search } from "@element-plus/icons-vue";
import { onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElTree } from "element-plus";

const instance = getCurrentInstance();
const { $http } = instance?.appContext.config.globalProperties;

let title1 = ref(""),
  title2 = ref(""),
  title3 = ref(""),
  title4 = ref("");

const total = ref();
const currentPage = ref(0);
const pageSize = ref(20);

const createAndViewDrawer = ref(false);

const standardReviseDrawer = ref(false);

const leftPanelWidth = ref(300); // 初始左边面板宽度

const input2 = ref("");

const currentNodeKey = ref("");

const currentTableRow = ref();

let selPaths = ref<string[]>();

const debounce = (
  callback: { apply: (arg0: any, arg1: any[]) => void },
  delay: number | undefined
) => {
  let tid: number | undefined;
  return function (...args: any) {
    tid && clearTimeout(tid);
    tid = setTimeout(() => {
      callback.apply(getCurrentInstance(), args);
    }, delay);
  };
};

const _ = window.ResizeObserver;
window.ResizeObserver = class ResizeObserver extends _ {
  constructor(callback: any) {
    callback = debounce(callback, 20);
    super(callback);
  }
};

onMounted(() => {
  // 获取传递的参数
  const router = useRouter();
  let name = router.currentRoute.value.query.docType;
  console.log(router.currentRoute.value);
  console.log("传递过来的参数是 ", name);
  //currentNodeKey.value = name == null ? "" : name.toString();
  loadTreeData(name == null ? "" : name.toString());
  // const ret = findLabelPath(treeData.value, currentNodeKey.value);
  // console.log(ret);
  // let paths: string[] = [];

  // ret?.forEach((r) => {
  //   paths.push(r.label);
  // });
  // console.log("paths = ", paths);
  // selPaths.value = paths;
  // search();
});

function findLabelPath(
  tree: any[],
  targetLabel: string,
  path: any[] = []
): any[] | null {
  console.log("查找匹配的树节点：" + targetLabel);
  for (const node of tree) {
    path.push(node);
    if (node.label === targetLabel) {
      console.log("匹配成功！");
      return path;
    }

    if (node.children) {
      const found = findLabelPath(node.children, targetLabel, path);
      if (found) {
        return found;
      }
    }

    path.pop();
  }

  return null;
}

const fileList = ref([]);

const handleRemove = (file: any, uploadFiles: any) => {
  console.log(file, uploadFiles);
};

const handlePreview = (uploadFile: any) => {
  console.log(uploadFile);
};

const uploadByRevise = ref(UploadInstance);

const handleExceed = (files: any[]) => {
  uploadByRevise.value!.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  uploadByRevise.value!.handleStart(file);
};

const beforeRemove = (uploadFile: { name: any }, uploadFiles: any) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  );
};

const standardForm = reactive({
  gongKaiBiaoZhun: "",
  chengRenBiaoZhun: "",
  yingYuHua: false,
  zhongWenHua: false,
  shiYongXing: "",
  gongChang: "",
  shangPinBie: "",
  guanliFanHao: "",
  zhiDingRi: "",
  zuoChengZhe: "",
  jianYinZhe: "",
  chengRenZhe: "",
  zhiDingLiYou: [
    { name: "法规", checked: false },
    { name: "安全性", checked: false },
    { name: "耐久性", checked: false },
    { name: "加工", checked: false },
    { name: "市场", checked: false },
    { name: "信赖性", checked: false },
    { name: "组立上", checked: false },
    { name: "其它", checked: false },
  ],
  guanLianGuiGeFaGui: [
    { name: "JIS", checked: false },
    { name: "MIS", checked: false },
    { name: "其它", checked: false },
  ],
  dingZhengRi: "",
  dingZhengNo: "",
  dingZhengLiYou: "",
});

const standardFormRef = ref(FormInstance);

const submitForm = () => {
  standardFormRef.value.validate((valid: any) => {
    if (valid) {
      // 表单验证通过，执行提交操作
      console.log("表单验证通过，提交数据：", standardForm);
    } else {
      // 表单验证失败
      return false;
    }
  });
};

const loadTreeData = (selNodeName) => {
  const url = "/getStandardClassification";
  $http
    .get(url)
    .then((response: { data: any }) => {
      console.log("查询结果", response.data);
      treeData.value = response.data;
      const ret = findLabelPath(treeData.value, selNodeName);
      console.log("匹配结果" + ret);
      let paths: string[] = [];
      ret?.forEach((r) => {
        paths.push(r.label);
      });
      console.log("paths = ", paths);
      console.log("node = " + selNodeName);
      setTimeout(() => {
        selPaths.value = paths;
        currentNodeKey.value = selNodeName;
        search(selNodeName);
      }, 1);
    })
    .catch((error: any) => {
      console.log(error);
    });
};
// const loadTreeData = async () => {
//   try {
//     const url = "/getStandardClassification";
//     const response = await $http.get(url);
//     console.log("查询结果", response.data);
//     treeData.value = response.data;
//   } catch (error) {
//     console.log(error);
//   }
// };

const filterTableData = () => {
  let text = input2.value;
  search(currentNodeKey.value, text);
};

const handleCurrentChange = (val: any) => {
  let ps = pageSize.value;
  currentPageTableData.value = tableData.value.slice(val * ps, (val + 1) * ps);
  console.log("==========================", ps);
  console.log(tableData.value);
  console.log(currentPageTableData.value);
};
const search = (typeName, filterText) => {
  console.log("search...");
  let url = "/getStandardsDocByTypeName?typeNames=" + typeName;
  console.log("filterText = " + filterText);
  if (filterText) {
    url += "&filterText=" + filterText;
  }
  console.log("url = " + url);
  $http
    .get(url)
    .then((response: { data: any }) => {
      console.log("查询结果", response.data);
      // this.bomInfos = [response.data];
      // this.expand_row_keys = [this.bomInfos[0].child_item_revision_uid];
      tableData.value = response.data;
      total.value = response.data == null ? 0 : response.data.length;
      currentPage.value = 0;
      handleCurrentChange(0);
    })
    .catch((error: any) => {
      console.log(error);
    });
  // $http
  //   .get(url)
  //   .then((response: any) => {
  //     console.log("search end.");
  //     console.log(response);
  //   })
  //   .catch((error: any) => {
  //     console.error(error);
  //   });
};

const watchProps = (item: any) => {
  console.log(item);
  console.log(item.PP8_PUBLIC);
  standardForm.gongKaiBiaoZhun = item.PP8_PUBLIC;
  standardForm.chengRenBiaoZhun = item.PP8_ACCEPT;
  standardForm.yingYuHua = item.PP8_ENGLISH && item.PP8_ENGLISH.length > 0;
  standardForm.zhongWenHua = item.PP8_CHINESE && item.PP8_CHINESE.length > 0;
  standardForm.gongChang = item.PP8_FACTORY;
  standardForm.shangPinBie = item.PP8_PRODUCT;
  standardForm.guanliFanHao = item.PITEM_ID;
  standardForm.zhiDingRi = item.PP8_CREATEDATE;
  standardForm.zuoChengZhe = item.PP8_AUTHOR;
  standardForm.jianYinZhe = item.PP8_CHECKOWNER;
  standardForm.chengRenZhe = item.PP8_ACCEPTOR;
  // standardForm.zhiDingLiYou = [item.MAKEREASON];
  // standardForm.guanLianGuiGeFaGui = ""
  standardForm.dingZhengRi = item.PP8_UPDATEDATE;
  standardForm.dingZhengNo = "";
  standardForm.dingZhengLiYou = item.PP8_UPDATEREASON;
  createAndViewDrawer.value = true;
};

const watchContent = (item: any) => {
  console.log(item);
  console.log(instance?.appContext.config.globalProperties.$baseURL);
  window.open(
    instance?.appContext.config.globalProperties.$baseURL +
      "/openDatasetByRevUid?uid=" +
      item.PUID,
    "_blank"
  );
};

const onTreeCurrentChange = (data: any, node: any) => {
  console.log(data, node);
  currentNodeKey.value = node.data.id;
  let paths: string[] = [];
  let curNode = node;
  do {
    paths.unshift(curNode.data.label);
    curNode = curNode.parent;
  } while (
    curNode != null &&
    curNode != undefined &&
    curNode.data.label != undefined
  );
  console.log("path is ", paths);
  selPaths.value = paths;
  let leafs = getAllChildrenLeaf(node);
  console.log("leafs = ", leafs);
  if (leafs == null || leafs.length == 0) return;
  let labels = leafs.map((leaf) => leaf.data.label);
  console.log("labels = ", labels);
  let labelJoin = labels.join(",");
  labelJoin = encodeURIComponent(labelJoin);
  search(labelJoin);
};

const getAllChildrenLeaf = (node: any) => {
  console.log("=>", node);
  let result = [];
  loadAllChildrenLeaf(node, result);
  return result;
};

const loadAllChildrenLeaf = (node: any, result: any[] = []) => {
  if (node.isLeaf) {
    result.push(node);
  } else {
    node.childNodes.forEach((childNode) => {
      loadAllChildrenLeaf(childNode, result);
    });
  }
};

const onTableCurrentChange = (data: any) => {
  console.log(data);
  currentTableRow.value = data;
};

const isTableSelRevisable = () => {
  return (
    currentTableRow.value != null && currentTableRow.value.releasedDate != null
  );
};

const isTableSelReleasable = () => {
  return (
    currentTableRow.value != null && currentTableRow.value.releasedDate == null
  );
};

const startResize = () => {
  document.addEventListener("mousemove", resize);
  document.addEventListener("mouseup", stopResize);
};

const resize = (event: MouseEvent) => {
  leftPanelWidth.value = event.clientX;
};

const stopResize = () => {
  document.removeEventListener("mousemove", resize);
  document.removeEventListener("mouseup", stopResize);
};

const defaultProps = {
  children: "children",
  label: "label",
};
const tableData = ref([]);
const currentPageTableData = ref([]);
const treeData = ref([]);
</script>
